package cn.yanji.service.impl.element;

import cn.hutool.core.collection.CollectionUtil;
import cn.yanji.pojo.ContentRow;
import cn.yanji.service.ExecuteService;
import cn.yanji.service.HttpService;
import cn.yanji.service.element.ContentService;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * @author yanji w2c17lin@qq.com
 * @since 2018/11/7 上午 11:12
 */
@Service
public class ContentServiceImpl implements ContentService {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private @Autowired ExecuteService executeService;
	private @Autowired HttpService httpService;

	@Override
	public List<ContentRow> contents() {
		List<ContentRow> contentRows = new ArrayList<>();
		for (; ; ) {
			/* 1) 获取当前页面题目信息 */
			contentRows.add(get());

			/* 2) 判断是否在最后一题了，如果是最后一题就直接返回了 */
			String nowNum = StringUtils.trim(executeService.element("spcurLine").getText());
			String allNum = StringUtils.trim(executeService.element("spcountLine").getText());
			if (StringUtils.equals(nowNum, allNum)) break;
			executeService.click("NextBtn");
		}
		return contentRows;
	}

	private ContentRow get() {

		/* 1) 获取题目内容和技巧内容 */
		WebElement skillGif = get(() -> executeService.click("SkillBtn"),
				() -> executeService.element("Skillimg").findElements(By.tagName("img")));
		WebElement content = executeService.element("divQuestion");
		WebElement skill = executeService.element("Skillimg");
		/* 2) 获取信息，如果有技巧图片用http下载后获取文件路径 */
		ContentRow contentRow = new ContentRow();
		contentRow.setContent(StringUtils.trim(content.getText()));
		contentRow.setSkill(StringUtils.trim(skill.getText()));
		if (Objects.nonNull(skillGif)) {
			String src = skillGif.getAttribute("src");
			logger.debug("获取到GIF路径地址: {}", src);
			contentRow.setSkillGif(httpService.download(src));
		}
		logger.debug("构造一个题目完成: {}", contentRow);

		/* 3) 关闭弹窗，要不然下一个按钮点击不到 */
		click(executeService.webDriver().findElement(By.id("popbox"))
				.findElement(By.xpath(".//div[@onclick='stopVoice();']")));
		return contentRow;
	}

	private void click(WebElement webElement) {
		try {
			webElement.click();
		} catch (ElementNotVisibleException ignored) {
		}
	}

	private WebElement get(Function function, Supplier<List<WebElement>> supplier) {
		/* 1) 获取执行操作前的元素ID */
		List<WebElement> beforeElements = supplier.get();
		String before = CollectionUtil.isNotEmpty(beforeElements) ?
				((RemoteWebElement) beforeElements.get(0)).getId() : null;
		/* 2) 执行操作 */
		function.exec();
		/* 3) 获取执行操作后的元素 */
		for (; ; ) {
			List<WebElement> afterElements = supplier.get();
			if (CollectionUtil.isEmpty(afterElements)) return null;
			String after = ((RemoteWebElement) afterElements.get(0)).getId();
			if (!StringUtils.equals(before, after)) return afterElements.get(0);
		}
	}

	@FunctionalInterface
	public interface Function {
		void exec();
	}

}
